#!/usr/bin/env python3
import subprocess
import datetime
import os

# 需要循环执行的 4 条命令，按需修改
CMDS = [
    "echo hello from cmd1",
    "ls -lh /tmp",
    "date",
    "uname -a"
]

LOG_FILE = "cmd_output.log"     # 日志文件名

def run_once():
    """执行一轮 4 条命令并写入日志"""
    with open(LOG_FILE, "a", encoding="utf-8") as f:
        # 每条命令前打印分隔符
        f.write("="*60 + "\n")
        f.write(f"{datetime.datetime.now():%F %T} - NEW ROUND\n")
        f.write("="*60 + "\n")

        for idx, cmd in enumerate(CMDS, 1):
            f.write(f"\n>>> [{idx}] {cmd}\n")
            f.flush()

            try:
                # shell=True 允许管道、重定向等 shell 特性
                completed = subprocess.run(
                    cmd,
                    shell=True,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.STDOUT,   # 合并 stderr
                    text=True                    # 直接得到 str
                )
                f.write(completed.stdout)
            except Exception as e:
                f.write(f"ERROR: {e}\n")

            f.flush()  # 立即落盘，防止异常丢失

if __name__ == "__main__":
    # 无限循环，每 10 秒一轮（可按需调整）
    import time
    print(f"开始记录，日志文件: {os.path.abspath(LOG_FILE)}")
    while True:
        run_once()
        time.sleep(10)